﻿using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace ShiQuan.Unity
{
    /// <summary>
    /// Unity 辅助对象
    /// </summary>
    public class UnityHelper
    {
        #region 单例

        private static readonly UnityHelper _instance = new UnityHelper();
        /// <summary>
        /// Unity 辅助对象
        /// </summary>
        public static UnityHelper Instance
        {
            get
            {
                return _instance;
            }
        }
        #endregion

        private readonly IUnityContainer _container = new UnityContainer();
        /// <summary>
        /// 获取容器
        /// </summary>
        public IUnityContainer Container
        {
            get { return _container; }
        }
        private UnityHelper()
        {
            var configuration = ConfigurationManager.GetSection(UnityConfigurationSection.SectionName) as UnityConfigurationSection;
            if (configuration != null)
            {
                configuration.Configure(_container);
            }
        }

        #region 获取对应接口的具体实现类
        /// <summary>
        /// 获取实现类(默认映射)
        /// </summary>
        /// <typeparam name="T">接口类型</typeparam>
        /// <returns>接口</returns>
        public T GetResolve<T>()
        {
            return _container.Resolve<T>();
        }
        /// <summary>
        /// 获取实现类(默认映射)带参数的
        /// </summary>
        /// <typeparam name="T">接口类型</typeparam>
        /// <param name="parameter">参数</param>
        /// <returns>接口</returns>
        public T GetResolve<T>(params ParameterOverride[] parameter)
        {
            return _container.Resolve<T>(parameter);
        }
        /// <summary>
        /// 获取实现类(指定映射)带参数的
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name"></param>
        /// <param name="parameter"></param>
        /// <returns>接口</returns>
        public T GetResolve<T>(string name, params ParameterOverride[] parameter)
        {
            return _container.Resolve<T>(name, parameter);
        }
        #endregion

        #region 判断接口是否被注册了
        /// <summary>
        /// 判断接口是否被实现了
        /// </summary>
        /// <typeparam name="T">接口类型</typeparam>
        /// <returns>bool</returns>
        public bool IsRegistered<T>()
        {
            return _container.IsRegistered<T>();
        }
        /// <summary>
        /// 判断接口是否被实现了
        /// </summary>
        /// <typeparam name="T">接口类型</typeparam>
        /// <param name="name">映射名称</param>
        /// <returns></returns>
        public bool IsRegistered<T>(string name)
        {
            return _container.IsRegistered<T>(name);
        }
        #endregion
    }
}
